package com.kingwood.algorithm.test200;

import java.util.*;

/**
 * @Author 22025812
 * @Description: TODO
 * @Date: 2024/3/29 9:53
 * @Modified By：
 * @Version 1.0
 */
public class Dijkstra {

    public static int getVirusSpreadTime(HashMap<Integer, ArrayList<int[]>> graph, int src, int n) {
        int[] dist = new int[n + 1];
        Arrays.fill(dist, Integer.MAX_VALUE);
        dist[src] = 0;

        boolean[] visited = new boolean[n + 1];
        // 0 : 当前节点
        // 1 : 源点到当前点距离
        PriorityQueue<int[]> needCheck = new PriorityQueue<int[]>((a, b) -> a[1] - b[1]);
        needCheck.add(new int[] { src, 0 });

        while (needCheck.size() > 0) {
            int u = needCheck.poll()[0];
            if (visited[u]) {
                continue;
            }

            visited[u] = true;

            if (!graph.containsKey(u)) {
                continue;
            }

            for (int[] edge : graph.get(u)) {
                int v = edge[0];
                int w = edge[1];
                if (!visited[v] && dist[u] + w < dist[v]) {
                    dist[v] = dist[u] + w;
                    needCheck.add(new int[] { v, dist[v] });
                }
            }
        }

        int ans = 0;
        for (int i = 1; i <= n; i++) {
            if (dist[i] == Integer.MAX_VALUE) {
                return -1;
            }
            ans = Math.max(ans, dist[i]);
        }

        return ans;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int m = scanner.nextInt();

        HashMap<Integer, ArrayList<int[]>> graph = new HashMap<>();

        for (int i = 0; i < m; i++) {
            int u = scanner.nextInt();
            int v = scanner.nextInt();
            int w = scanner.nextInt();

            if (!graph.containsKey(u)) {
                graph.put(u, new ArrayList<>());
            }

            graph.get(u).add(new int[]{v, w});
        }

        int src = scanner.nextInt();
        System.out.println(getVirusSpreadTime(graph, src, n));
    }
}
